package com.pinoc.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TaskManager {
	private final ExecutorService executorService;

	public TaskManager(int threadCount) {
		executorService = Executors.newFixedThreadPool(threadCount);
	}

	public <T> List<T> executeTasks(List<Callable<T>> tasks) throws InterruptedException {
		List<T> results = new ArrayList<>();

		// 创建CountDownLatch，计数器的数量为任务的数量
		CountDownLatch countDownLatch = new CountDownLatch(tasks.size());

		// 提交任务
		List<Future<T>> futures = new ArrayList<>();
		for (Callable<T> task : tasks) {
			Future<T> future = executorService.submit(() -> {
				try {
					T result = task.call();
					return result;
				} finally {
					// 计数器减一
					countDownLatch.countDown();
				}
			});
			futures.add(future);
		}

		// 等待所有任务执行完成
		countDownLatch.await();

		// 获取任务结果
		for (Future<T> future : futures) {
			try {
				T result = future.get();
				results.add(result);
			} catch (Exception e) {
				// 异常处理
			}
		}

		// 关闭线程池
		executorService.shutdown();
		return results;
	}

	public static void main(String[] args) {
		UUID uuid = UUID.randomUUID();

		String s = uuid.toString();
		System.out.println(s.replaceAll("-",""));
	}
}
